import api from "../common/api";
const config = require("../utils/config");

// 通过坐标获取城市信息缓存
const cityCache = {};
// 设备坐标缓存
let locationCache = null;
// 手动设置临时城市 {city, cityCode}
let cityTemporary = null;
const locationBehavior = Behavior({
  behaviors: [],
  data: {
    myBehaviorData: {},
    $cityReality: {}, //设备真实所处城市信息
  },
  attached: function () {},
  methods: {
    // 查看位置是否授权
    getScopeUserLocation() {
      return new Promise((resolve, reject) => {
        wx.getSetting({
          success(res) {
            if (res.authSetting["scope.userLocation"]) {
              resolve();
            } else {
              reject();
            }
          },
          fail() {
            reject();
          },
        });
      });
    },

    // 获取微信地理坐标经纬度（前提是授权了位置）
    getWxLocationBe() {
      if (locationCache) return Promise.resolve(locationCache);
      return new Promise((resolve, reject) => {
        wx.getLocation({
          type: "gcj02",
          isHighAccuracy: true,
          success(res) {
            locationCache = res;
            wx.setStorageSync("latAndLon", res);
            resolve(res);
          },
          fail(err) {
            let lon = wx.getStorageSync("latAndLon");
            if (lon) {
              resolve(lon);
            }
            reject(err);
          },
        });
      });
    },

    // 获取经纬度带上错误异常处理的弹窗（前提是授权了位置）
    getWxLocationWithErrorHandler() {
      if (locationCache) return Promise.resolve(locationCache);
      return new Promise((resolve, reject) => {
        wx.getLocation({
          type: "gcj02",
          isHighAccuracy: true,
          success(res) {
            locationCache = res;
            resolve(res);
          },
          fail(err) {
            if (!err) return reject();
            if (/LOCATIONSWITCHOFF/.test(err.errMsg)) {
              wx.showModal({
                content: "设备未开启定位功能！",
                confirmText: "知道了",
                showCancel: false,
              });
            }
            if (/permission/.test(err.errMsg)) {
              wx.showModal({
                content: "设备或微信未开启位置授权！",
                confirmText: "知道了",
                showCancel: false,
              });
            }
            reject(err);
          },
        });
      });
    },

    // 根据经纬度 获取当前城市 reality: 设备真实坐标
    getCurrentCityByLatlng(latitude, longitude, reality = false) {
      let key = [latitude, longitude].join(",");
      if (cityCache[key]) {
        return Promise.resolve(cityCache[key]);
      }

      return new Promise((resolve, reject) => {
        const defaultResult = {
          cityCode: "310000",
          province: "",
          city: "上海市",
          district: "",
          location: { lat: latitude, lng: longitude },
        };

        // 10秒默认
        setTimeout(() => {
          resolve(defaultResult);
        }, 10 * 1000);

        wx.request({
          url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${config.key}`,
          success: (res) => {
            try {
              const info = res.data.result.ad_info;
              let currentCity = (cityCache[key] = {
                cityCode: info.city_code.substring(3),
                province: info.province,
                city: info.city,
                district: info.district,
                location: { lat: latitude, lng: longitude },
              });

              if (reality) {
                this.data.$cityReality = currentCity;
              }

              resolve(currentCity);
            } catch (error) {
              resolve(defaultResult);
            }
          },
        });
      });
    },

    // 获取小区列表（根据当前城市信息）
    getVillageBe(currentCity, subscribe) {
      return new Promise((resolve, reject) => {
        api.villageList(
          {
            lat: currentCity.location.lat,
            lng: currentCity.location.lng,
            pageNo: 1,
            rows: 30,
            city: currentCity.city,
            province: currentCity.province,
            area: currentCity.district,
            isExternal: subscribe ? true : null,
          },
          (res) => {
            if (!res.data.isSuccess) throw new Error("获取小区列表error");
            resolve(res.data.content.rows);
          }
        );
      });
    },

    // 获取当前城市
    getCityBe(customReject = false) {
      const app = getApp();
      const city = app.globalData._wx_city || wx.getStorageSync("_wx_city");
      if (city) {
        this.setWxCityBe(city);
        return Promise.resolve(city);
      }

      return new Promise((resolve, reject) => {
        this.getWxLocationBe()
          .then((res) => {
            return this.getCurrentCityByLatlng(res.latitude, res.longitude);
          })
          .then((res) => {
            const city = res.city;
            this.setWxCityBe(city);
            resolve(city);
          })
          .catch(() => {
            if (customReject) {
              reject();
            } else {
              const city = "上海市";
              resolve(city);
            }
          });
      });
    },

    /**
     * 优先使用设备坐标城市
     * 其次登录ip城市
     * @returns
     */
    getCityInfoNew() {
      if (cityTemporary) return Promise.resolve(cityTemporary);
      return this.getScopeUserLocation()
        .then(() => {
          return this.getWxLocationBe();
        })
        .then((res) => {
          return this.getCurrentCityByLatlng(res.latitude, res.longitude);
        })
        .catch(() => {
          let { loginCity, loginCityCode } = getApp().globalData;
          if (loginCity && loginCityCode) {
            return Promise.resolve({ city: loginCity, cityCode: loginCityCode });
          } else {
            return Promise.reject();
          }
        });
    },

    /**
     * 手动设置城市（暂时的）
     * @param {*} info city cityCode
     */
    setCityTemporary(info) {
      cityTemporary = info;
    },

    setWxCityBe(city) {
      console.log("设置微信城市", city);
      const app = getApp();
      if (
        app.globalData.sessionUser &&
        app.globalData.sessionUser.extProps &&
        !app.globalData.sessionUser.extProps.city
      ) {
        app.globalData.sessionUser.extProps.city = city;

        wx.gio("setUser", {
          city_ppl: city,
        });
      }
      app.globalData._wx_city = city;
      wx.setStorageSync("_wx_city", city);
    },
  },
});

export default locationBehavior;
